package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Employee;
import com.example.entity.EmployeeDetail;
import com.example.entity.Position;
import com.example.entity.Salary;
import com.example.entity.Department;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import com.example.exception.CustomException;
import com.example.mapper.EmployeeMapper;
import com.example.mapper.PositionMapper;
import com.example.mapper.SalaryMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.example.entity.SalaryImport;
import com.example.excel.SalaryImportListener;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

@Service
public class SalaryService {

    @Resource
    private SalaryMapper salaryMapper;
    
    @Resource
    private EmployeeMapper employeeMapper;
    
    @Resource
    private PositionMapper positionMapper;
    
    @Resource
    private EmployeeDetailService employeeDetailService;
    
    @Resource
    private DepartmentService departmentService;
    
    /**
     * 新增
     */
    public void add(Salary salary) {
        // 检查员工是否存在
        Employee employee = employeeMapper.selectById(salary.getEmployeeId());
        if (employee == null) {
            throw new CustomException("400", "员工不存在");
        }
        
        // 检查是否已存在该员工当月薪资记录
        Salary existSalary = salaryMapper.selectByEmployeeIdAndMonth(salary.getEmployeeId(), salary.getSalaryMonth());
        if (existSalary != null) {
            throw new CustomException("400", "该员工当月薪资记录已存在");
        }
        
        // 计算实发工资
        calculateActualSalary(salary);
        
        // 设置默认状态为待发放
        if (ObjectUtil.isEmpty(salary.getStatus())) {
            salary.setStatus("PENDING");
        }
        
        salaryMapper.insert(salary);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        Salary salary = salaryMapper.selectById(id);
        if (salary != null && "PAID".equals(salary.getStatus())) {
            throw new CustomException("400", "已发放的薪资记录不能删除");
        }
        salaryMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Salary salary) {
        Salary dbSalary = salaryMapper.selectById(salary.getId());
        if (dbSalary != null && "PAID".equals(dbSalary.getStatus())) {
            throw new CustomException("400", "已发放的薪资记录不能修改");
        }
        
        // 计算实发工资
        calculateActualSalary(salary);
        
        salaryMapper.updateById(salary);
    }
    
    /**
     * 计算实发工资
     */
    public void calculateActualSalary(Salary salary) {
        BigDecimal actualSalary = BigDecimal.ZERO;
        
        // 基本工资
        if (salary.getBaseSalary() != null) {
            actualSalary = actualSalary.add(salary.getBaseSalary());
        }
        
        // 绩效工资
        if (salary.getPerformance() != null) {
            actualSalary = actualSalary.add(salary.getPerformance());
        }
        
        // 奖金
        if (salary.getBonus() != null) {
            actualSalary = actualSalary.add(salary.getBonus());
        }
        
        // 扣除金额
        if (salary.getDeduction() != null) {
            actualSalary = actualSalary.subtract(salary.getDeduction());
        }
        
        salary.setActualSalary(actualSalary);
    }

    /**
     * 根据ID查询
     */
    public Salary selectById(Integer id) {
        return salaryMapper.selectById(id);
    }
    
    /**
     * 根据员工ID和月份查询
     */
    public Salary selectByEmployeeIdAndMonth(Integer employeeId, String salaryMonth) {
        return salaryMapper.selectByEmployeeIdAndMonth(employeeId, salaryMonth);
    }

    /**
     * 查询全部
     */
    public List<Salary> selectAll(Salary salary) {
        return salaryMapper.selectAll(salary);
    }
    
    /**
     * 根据员工ID查询薪资记录
     */
    public List<Salary> selectByEmployeeId(Integer employeeId) {
        return salaryMapper.selectByEmployeeId(employeeId);
    }
    
    /**
     * 根据月份查询薪资记录
     */
    public List<Salary> selectBySalaryMonth(String salaryMonth) {
        return salaryMapper.selectBySalaryMonth(salaryMonth);
    }
    
    /**
     * 批量发放薪资
     */
    public void paySalaryBatch(List<Integer> ids) {
        salaryMapper.updateStatusBatch(ids, "PAID");
    }
    
    /**
     * 生成薪资记录
     */
    public void generateSalary(String salaryMonth) {
        // 查询所有员工
        Employee queryEmployee = new Employee();
        queryEmployee.setStatus("ACTIVE"); // 只处理在职员工
        List<Employee> employees = employeeMapper.selectAll(queryEmployee);
        
        for (Employee employee : employees) {
            // 检查是否已存在该员工当月薪资记录
            Salary existSalary = salaryMapper.selectByEmployeeIdAndMonth(employee.getId(), salaryMonth);
            if (existSalary != null) {
                continue; // 已存在则跳过
            }
            
            // 获取员工详情信息
            EmployeeDetail employeeDetail = employeeDetailService.selectByEmployeeId(employee.getId());
            if (employeeDetail == null) {
                continue; // 无详情信息则跳过
            }
            
            // 获取职位信息
            Position position = positionMapper.selectById(employeeDetail.getPositionId());
            if (position == null) {
                continue; // 无职位信息则跳过
            }
            
            // 创建薪资记录
            Salary salary = new Salary();
            salary.setEmployeeId(employee.getId());
            salary.setBaseSalary(position.getBaseSalary());
            salary.setPerformance(BigDecimal.ZERO); // 默认绩效为0
            salary.setBonus(BigDecimal.ZERO); // 默认奖金为0
            salary.setDeduction(BigDecimal.ZERO); // 默认扣除为0
            salary.setSalaryMonth(salaryMonth);
            salary.setStatus("PENDING");
            
            // 计算实发工资
            calculateActualSalary(salary);
            
            // 保存薪资记录
            salaryMapper.insert(salary);
        }
    }
    
    /**
     * 获取薪资统计数据
     * @param departmentId 部门ID（可选）
     * @param employeeId 员工ID（可选）
     * @param startMonth 开始月份（可选，格式：yyyy-MM）
     * @param endMonth 结束月份（可选，格式：yyyy-MM）
     * @return 统计结果
     */
    public Map<String, Object> getStatistics(Integer departmentId, Integer employeeId, String startMonth, String endMonth) {
        Map<String, Object> result = new HashMap<>();
        
        // 构建查询条件
        Salary querySalary = new Salary();
        if (employeeId != null) {
            querySalary.setEmployeeId(employeeId);
        }
        
        // 查询符合条件的薪资记录
        List<Salary> salaryList = salaryMapper.selectAll(querySalary);
        
        // 如果有部门ID筛选，需要进一步过滤
        if (departmentId != null) {
            salaryList = salaryList.stream().filter(salary -> {
                // 获取员工详情
                EmployeeDetail detail = employeeDetailService.selectByEmployeeId(salary.getEmployeeId());
                return detail != null && departmentId.equals(detail.getDepartmentId());
            }).collect(Collectors.toList());
        }
        
        // 如果有时间范围筛选，需要进一步过滤
        if (startMonth != null && endMonth != null) {
            salaryList = salaryList.stream().filter(salary -> {
                String month = salary.getSalaryMonth();
                return month != null && month.compareTo(startMonth) >= 0 && month.compareTo(endMonth) <= 0;
            }).collect(Collectors.toList());
        } else if (startMonth != null) {
            salaryList = salaryList.stream().filter(salary -> {
                String month = salary.getSalaryMonth();
                return month != null && month.compareTo(startMonth) >= 0;
            }).collect(Collectors.toList());
        } else if (endMonth != null) {
            salaryList = salaryList.stream().filter(salary -> {
                String month = salary.getSalaryMonth();
                return month != null && month.compareTo(endMonth) <= 0;
            }).collect(Collectors.toList());
        }
        
        // 如果没有数据，返回空结果
        if (salaryList.isEmpty()) {
            result.put("totalSalary", 0);
            result.put("avgSalary", 0);
            result.put("maxSalary", 0);
            result.put("minSalary", 0);
            result.put("departmentSalary", Collections.emptyList());
            result.put("monthlySalary", Collections.emptyList());
            result.put("salaryList", Collections.emptyList());
            return result;
        }
        
        // 计算总薪资
        BigDecimal totalSalary = salaryList.stream()
                .map(Salary::getActualSalary)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 计算平均薪资
        BigDecimal avgSalary = BigDecimal.ZERO;
        if (!salaryList.isEmpty()) {
            avgSalary = totalSalary.divide(new BigDecimal(salaryList.size()), 2, RoundingMode.HALF_UP);
        }
        
        // 计算最高薪资
        BigDecimal maxSalary = salaryList.stream()
                .map(Salary::getActualSalary)
                .filter(Objects::nonNull)
                .max(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
        
        // 计算最低薪资
        BigDecimal minSalary = salaryList.stream()
                .map(Salary::getActualSalary)
                .filter(Objects::nonNull)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
        
        // 按部门分组统计
        Map<String, BigDecimal> departmentSalary = new HashMap<>();
        for (Salary salary : salaryList) {
            // 获取员工详情
            EmployeeDetail detail = employeeDetailService.selectByEmployeeId(salary.getEmployeeId());
            if (detail != null) {
                // 获取部门名称
                String departmentName = "未知部门";
                if (detail.getDepartmentId() != null) {
                    Department department = departmentService.selectById(detail.getDepartmentId());
                    if (department != null) {
                        departmentName = department.getName();
                    }
                }
                
                // 累加部门薪资
                BigDecimal deptSalary = departmentSalary.getOrDefault(departmentName, BigDecimal.ZERO);
                if (salary.getActualSalary() != null) {
                    deptSalary = deptSalary.add(salary.getActualSalary());
                }
                departmentSalary.put(departmentName, deptSalary);
            }
        }
        
        // 转换为前端需要的格式
        List<Map<String, Object>> departmentSalaryList = departmentSalary.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", entry.getKey());
                    map.put("value", entry.getValue());
                    return map;
                })
                .collect(Collectors.toList());
        
        // 按月份分组统计
        Map<String, BigDecimal> monthlySalary = new TreeMap<>(); // 使用TreeMap保证月份有序
        for (Salary salary : salaryList) {
            if (salary.getSalaryMonth() != null && salary.getActualSalary() != null) {
                BigDecimal monthTotal = monthlySalary.getOrDefault(salary.getSalaryMonth(), BigDecimal.ZERO);
                monthTotal = monthTotal.add(salary.getActualSalary());
                monthlySalary.put(salary.getSalaryMonth(), monthTotal);
            }
        }
        
        // 转换为前端需要的格式
        List<Map<String, Object>> monthlySalaryList = monthlySalary.entrySet().stream()
                .map(entry -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("month", entry.getKey());
                    map.put("total", entry.getValue());
                    return map;
                })
                .collect(Collectors.toList());
        
        // 组装结果
        result.put("totalSalary", totalSalary);
        result.put("avgSalary", avgSalary);
        result.put("maxSalary", maxSalary);
        result.put("minSalary", minSalary);
        result.put("departmentSalary", departmentSalaryList);
        result.put("monthlySalary", monthlySalaryList);
        result.put("salaryList", salaryList);
        
        return result;
    }
    
    /**
     * 批量导入薪资数据
     * @param file Excel文件
     * @return 导入结果
     */
    public Map<String, Object> importSalary(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new CustomException("400", "请选择要导入的Excel文件");
        }
        
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
            throw new CustomException("400", "文件格式不正确，请上传Excel文件");
        }
        
        // 创建Excel监听器
        SalaryImportListener listener = new SalaryImportListener(employeeMapper, salaryMapper, this);
        
        // 读取Excel
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcel.read(file.getInputStream(), SalaryImport.class, listener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
        
        // 返回导入结果
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", listener.getTotalCount());
        result.put("successCount", listener.getSuccessCount());
        result.put("failCount", listener.getFailCount());
        result.put("errorMessages", listener.getErrorMessages());
        
        return result;
    }
    
    /**
     * 生成薪资导入模板
     */
    public void generateImportTemplate(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("薪资导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        // 创建示例数据
        List<SalaryImport> list = new ArrayList<>();
        SalaryImport example = new SalaryImport();
        example.setEmployeeName("张三");
        example.setSalaryMonth("2023-10");
        example.setBaseSalary(new BigDecimal("8000"));
        example.setPerformance(new BigDecimal("2000"));
        example.setBonus(new BigDecimal("500"));
        example.setDeduction(new BigDecimal("1000"));
        example.setStatus("PENDING");
        list.add(example);
        
        // 导出模板
        EasyExcel.write(response.getOutputStream(), SalaryImport.class).sheet("薪资数据").doWrite(list);
    }
}